package com.zwt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zwt.annotation.NoAuthAnnotation;
import com.zwt.constant.UrlConstant;
import com.zwt.model.TAccountUser;
import com.zwt.result.ResultBean;
import com.zwt.result.ResultCode;
import com.zwt.service.ApiService;
import com.zwt.util.TTime;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zwt on 2018/9/6.
 * app 发送短信
 */
@NoAuthAnnotation
@RestController
@RequestMapping("/app/sms")
public class SmsController {

    private static Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private UrlConstant urlConstant;

    @Autowired
    private ApiService apiService;

    /**
     * 注册发送验证码
     * @param phone
     * @return
     */
    @RequestMapping("reg")
    public ResultBean<JSONObject> reg(@RequestParam String phone){
        ResultBean<JSONObject> result = new ResultBean<>();
        String requestUrl = urlConstant.getRegSms();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("phone",phone);
        String json = apiService.getJson(requestUrl, map, urlConstant.getHost());
        logger.info("调用发送注册验证码接口返回数据"+json);
        if(StringUtils.isBlank(json) || json.contains("通信失败")){
            logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"通信失败"+json);
            result.setMessage("系统异常，请重试");
            return result;
        }
        result = JSON.parseObject(json, ResultBean.class);
        return result;
    }


    /**
     * 注册发送验证码
     * @param phone
     * @return
     */
    @RequestMapping("login")
    public ResultBean<JSONObject> login(@RequestParam String phone){
        ResultBean<JSONObject> result = new ResultBean<>();
        String requestUrl = urlConstant.getLoginSms();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("phone",phone);
        String json = apiService.getJson(requestUrl, map, urlConstant.getHost());
        logger.info("调用发送注册验证码接口返回数据"+json);
        if(StringUtils.isBlank(json) || json.contains("通信失败")){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"通信失败"+json);
            result.setMessage("系统异常，请重试");
            return result;
        }
        result = JSON.parseObject(json, ResultBean.class);
        return result;
    }
}
